package com.x.listener;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebListener;

/**
 * ClassName: MyApplicationListener
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.08.30 16:19
 */

@WebListener
public class MyApplicationListener implements ServletContextListener, ServletContextAttributeListener{
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        System.out.println(servletContext.hashCode()+" 应用域初始化了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        System.out.println(servletContext.hashCode()+" 应用域销毁了");
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent scae) {
        ServletContext application = scae.getServletContext();
        String name = scae.getName();
        String value = (String) scae.getValue();
        System.out.println(application.hashCode()+"应用域增加了key:"+name+", value:"+value);
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent scae) {
        ServletContext application = scae.getServletContext();
        String name = scae.getName();
        String value = (String) scae.getValue();
        System.out.println(application.hashCode()+"应用域删除了key:"+name+", value:"+value);
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent scae) {
        ServletContext application = scae.getServletContext();
        String name = scae.getName();
        String value = (String) scae.getValue();//获取的旧的值
        String newValue = (String) application.getAttribute(name);
        System.out.println(application.hashCode()+"应用域修改了key:"+name+", value:"+value+", 新value值为"+newValue);

    }
}
